<!-- 表单设计器 -->
<template>
  <div class="form-designer-container">
    <div class="form-designer-header">
      <el-button-group>
        <el-button
          type="primary"
          :loading="saveLoading"
          @click="handleSave"
        >
          <el-icon><Save /></el-icon>
          保存
        </el-button>
        <el-button @click="handleClose">
          <el-icon><Close /></el-icon>
          关闭
        </el-button>
      </el-button-group>
    </div>
    
    <v-form-designer
      ref="vfdRef"
      :designer-config="designerConfig"
      :form-config="formConfig"
      @save="handleSave"
      @preview="handlePreview"
    ></v-form-designer>

    <!-- 预览对话框 -->
    <el-dialog
      v-model="previewDialogVisible"
      title="表单预览"
      width="60%"
      destroy-on-close
    >
      <v-form-render
        v-if="previewDialogVisible"
        :form-json="previewFormJson"
        :form-data="previewFormData"
        :option-data="previewOptionData"
        ref="previewFormRef"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="previewDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="handlePreviewSubmit">提交</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 保存表单对话框 -->
    <el-dialog
      v-model="saveDialogVisible"
      title="保存表单"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        ref="saveFormRef"
        :model="saveFormData"
        :rules="saveFormRules"
        label-width="80px"
      >
        <el-form-item label="表单名称" prop="formName">
          <el-input
            v-model="saveFormData.formName"
            placeholder="请输入表单名称"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="saveFormData.remark"
            type="textarea"
            placeholder="请输入备注信息"
            :rows="3"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="saveDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            :loading="saveLoading"
            @click="submitSaveForm"
          >
            确定保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus'
import { VFormDesigner, VFormRender } from 'vform3-builds'
import 'vform3-builds/dist/designer.style.css'

export default {
  name: 'FormDesigner',
  
  components: {
    VFormDesigner,
    VFormRender
  },
  
  data() {
    return {
      // 设计器配置
      designerConfig: {
        languageMenu: false,
        clearable: true,
        previewable: true,
        importable: true,
        exportable: true,
        generateCode: true,
        toolbarMaxWidth: 300,
        toolbarMinWidth: 200,
        formTemplates: [
          {
            templateName: '基础表单',
            templateJson: {
              widgetList: [
                {
                  type: 'input',
                  icon: 'text-field',
                  formItemFlag: true,
                  options: {
                    name: 'input_1',
                    label: '单行文本',
                    labelAlign: '',
                    type: 'text',
                    defaultValue: '',
                    placeholder: '请输入',
                    columnWidth: '200px',
                    size: '',
                    labelWidth: null,
                    labelHidden: false,
                    disabled: false,
                    hidden: false,
                    required: false,
                    requiredHint: '',
                    validation: '',
                    validationHint: '',
                    pattern: '',
                    patternHint: '',
                    validator: '',
                    showWordLimit: false,
                    maxLength: null,
                    showPassword: false,
                    clearable: true,
                    prefixIcon: '',
                    suffixIcon: '',
                    prepend: '',
                    append: '',
                    customClass: [],
                    labelIconClass: null,
                    labelIconPosition: 'rear',
                    labelTooltip: null,
                    onCreated: '',
                    onMounted: '',
                    onInput: '',
                    onChange: '',
                    onFocus: '',
                    onBlur: '',
                    onValidate: '',
                    onAppendButtonClick: '',
                    onPrependButtonClick: '',
                    onSuffixIconClick: '',
                    onPrefixIconClick: ''
                  },
                  id: 'input_1'
                }
              ],
              formConfig: {
                modelName: 'formData',
                refName: 'vForm',
                rulesName: 'rules',
                labelWidth: 80,
                labelPosition: 'left',
                size: '',
                labelAlign: 'label-left-align',
                cssCode: '',
                customClass: [],
                functions: '',
                layoutType: 'PC',
                jsonVersion: 1,
                onFormCreated: '',
                onFormMounted: '',
                onFormDataChange: ''
              }
            }
          }
        ]
      },
      
      // 表单配置
      formConfig: {
        modelName: 'formData',
        size: 'default',
        labelPosition: 'right',
        labelWidth: 80,
        disabled: false,
        hideRequiredMark: false,
        labelCol: { span: 6 },
        wrapperCol: { span: 18 }
      },
      
      // 预览相关
      previewDialogVisible: false,
      previewFormJson: {},
      previewFormData: {},
      previewOptionData: {},
      
      // 保存相关
      saveDialogVisible: false,
      saveLoading: false,
      saveFormData: {
        formName: '',
        remark: ''
      },
      saveFormRules: {
        formName: [
          { required: true, message: '请输入表单名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  
  mounted() {
    this.loadSavedForm()
  },
  
  methods: {
    // 打开保存对话框
    openSaveDialog(formJson) {
      if (formJson.formConfig?.formName) {
        this.saveFormData.formName = formJson.formConfig.formName
      }
      this.saveDialogVisible = true
    },
    
    // 提交保存表单
    submitSaveForm() {
      if (!this.$refs.saveFormRef) return
      
      this.$refs.saveFormRef.validate(async (valid) => {
        if (!valid) return
        
        const formJson = this.$refs.vfdRef?.getFormJson()
        if (!formJson) return
        
        // 更新表单配置中的名称
        if (!formJson.formConfig) {
          formJson.formConfig = {}
        }
        formJson.formConfig.formName = this.saveFormData.formName
        
        this.saveLoading = true
        const data = {
          formJson: JSON.stringify(formJson),
          formName: this.saveFormData.formName,
          desc: this.saveFormData.remark
        }
        
        try {
          const res = await this.$post('/insertFormConfig', data)
          if (res.code === 200) {
            ElMessage({
              type: 'success',
              message: '表单保存成功',
              duration: 2000
            })
            this.saveDialogVisible = false
            // 重置表单
            this.saveFormData.formName = ''
            this.saveFormData.remark = ''
          } else {
            ElMessage({
              type: 'error',
              message: res.msg || '保存失败，请重试',
              duration: 3000
            })
          }
        } catch (err) {
          console.error('保存表单失败:', err)
          ElMessage({
            type: 'error',
            message: '保存失败，请稍后重试',
            duration: 3000
          })
        } finally {
          this.saveLoading = false
        }
      })
    },
    
    // 保存按钮点击事件
    handleSave() {
      const formJson = this.$refs.vfdRef?.getFormJson()
      if (formJson) {
        this.openSaveDialog(formJson)
      }
    },
    
    // 关闭表单设计器
    handleClose() {
      ElMessageBox.confirm('确定要关闭表单设计器吗？未保存的内容将会丢失', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$router.push('/workflow/form-config')
      }).catch(() => {})
    },
    
    // 预览表单
    handlePreview(formJson) {
      this.previewFormJson = formJson
      this.previewFormData = {}
      this.previewOptionData = {}
      this.previewDialogVisible = true
    },
    
    // 预览表单提交
    async handlePreviewSubmit() {
      if (!this.$refs.previewFormRef) return
      
      try {
        const valid = await this.$refs.previewFormRef.validate()
        if (!valid) {
          ElMessage.warning('请完善表单信息')
          return
        }
        
        const formData = await this.$refs.previewFormRef.getFormData()
        console.log('表单数据:', formData)
        
        ElMessage.success('表单提交成功')
        this.previewDialogVisible = false
      } catch (error) {
        console.error('表单提交失败:', error)
        ElMessage.error('提交失败，请稍后重试')
      }
    },
    
    // 加载已保存的表单配置
    async loadSavedForm() {
      try {
        const formId = this.$route.query.id
        if (!formId) return
        
        const res = await this.$get('/getFormDesign', { id: formId })
        if (res.code === 200 && res.data) {
          const formJson = JSON.parse(res.data.formJson)
          this.$refs.vfdRef?.setFormJson(formJson)
        }
      } catch (error) {
        console.error('加载表单配置失败:', error)
        ElMessage.error('加载失败，请刷新页面重试')
      }
    }
  }
}
</script>

<style lang="scss">
.form-designer-container {
  height: 100vh;
  width: 100%;
  background-color: #f5f7fa;
  display: flex;
  flex-direction: column;
  
  .form-designer-header {
    padding: 10px 20px;
    background-color: #fff;
    border-bottom: 1px solid #dcdfe6;
    display: flex;
    justify-content: flex-end;
    
    .el-button-group {
      .el-button {
        display: flex;
        align-items: center;
        gap: 4px;
      }
    }
  }
  
  :deep(.v-form-designer) {
    flex: 1;
    height: calc(100vh - 60px);
  }
}

// 覆盖一些默认样式
:deep(.v-form-designer) {
  .designer-container {
    background-color: #fff;
  }
  
  .widget-list-container {
    background-color: #f5f7fa;
  }
  
  .form-widget-container {
    background-color: #fff;
  }
  
  .property-panel {
    background-color: #fff;
  }
}

// 预览对话框样式
:deep(.el-dialog__body) {
  padding: 20px;
  
  .v-form-container {
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
  }
}

// 保存对话框样式
:deep(.el-dialog__body) {
  padding: 20px 30px;
  
  .el-form-item {
    margin-bottom: 22px;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
}
</style>